package com.kgcx.order.common;

import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MqttListenerCallback implements MqttCallback {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private MqttClient mqttClient;

    public MqttListenerCallback(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连

        logger.info("连接断开，可以做重连");

        logger.error(" MQTT客户端连接报错：\" with cause \"" + cause.getMessage() + "\" Reason code "
                + ((MqttException)cause).getReasonCode() + "\" Cause \""
                + ((MqttException)cause).getCause() +  "\"");
        if(!mqttClient.isConnected())
        {
            try
            {
                mqttClient.reconnect();
                mqttClient.subscribe("mileageRecordUpload",1);

                logger.info("客服端重连成功！");
            }
            catch (MqttException e)
            {
                e.printStackTrace();
                logger.error("客服端重连失败！！");
            }
        }

    }
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题:"+ s);
        logger.info("接收消息Qos:"+mqttMessage.getQos());
        logger.info("接收消息内容:"+new String(mqttMessage.getPayload()));

        try
        {
            String payload = new String(mqttMessage.getPayload());
        }
        catch(Exception e)
        {
            logger.info("mqtt接收消息处理失败");
            logger.error(e.getMessage());
        }
    }
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        // publish后会执行到这里
        System.out.println("deliveryComplete---------"+ iMqttDeliveryToken.isComplete());
    }
}
